export const ACCESS_TOKEN = 'access_token'
import Vue from 'vue'
import { login } from '@/api/login'

const user = {
  state: {
    token: '',
    username: '',
    userId: 0,
    nickname: '',
    avatar: '',
    // menus: [],
    roles: [],
    info: {}
  },

  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_AVATAR (state, avatar) {
      state.avatar = avatar
    },
    SET_INFO: (state, info) => {
      state.info = info
    },
    SET_USER_ID (state, id) {
      state.userId = id
    },
    SET_USER_INFO: (state, result) => {
      state.userId = result.userId
      state.avatar = result.avatar ? result.avatar : '/img/avatar.png'
      state.username = result.username
      state.nickname = result.nickname
    },

    // SET_MENUS (state, menus) {
    //   state.menus = menus
    // },
    SET_ROLES: (state, roles) => {
      state.roles = roles
    }
  },

  actions: {
    // 登录
    ActionLogin ({ commit }, userInfo) {
      return new Promise((resolve, reject) => {
        login(userInfo).then(res => {
          const result = res.data
          if (res.code === 0) {
            Vue.ls.set(ACCESS_TOKEN, result.access_token, 7 * 24 * 60 * 60 * 1000)
            Vue.ls.set("user", result.user, 7 * 24 * 60 * 60 * 1000)
            commit('SET_TOKEN', result.access_token)
            commit('SET_USER_INFO', result.user)
            resolve(res)
          } else {
            reject(res.msg)
          }
        }).catch(error => {
          reject(error)
        })
      })
    },
  }
}

export default user